package com.dgut.healthreportmanage.service;

import com.dgut.healthreportmanage.mapper.AdminMapper;
import com.dgut.healthreportmanage.pojo.Admin;
import com.dgut.healthreportmanage.pojo.AdminEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashSet;

@Service
public class AdminEntityServiceImpl implements UserDetailsService {
    @Autowired
    private AdminMapper adminMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Admin adminByName = adminMapper.getAdminByName(username);
        if (adminByName != null) {
            //填充权限
            Collection<SimpleGrantedAuthority> authorities = new HashSet<SimpleGrantedAuthority>();
            if (adminByName.getAdminId() == 1) {
                authorities.add(new SimpleGrantedAuthority("SysAdmin"));
            }
            authorities.add(new SimpleGrantedAuthority("Admin"));
            return new AdminEntity(username, new BCryptPasswordEncoder().encode(adminByName.getPassword()), authorities);
        }
        else {
            System.out.println(username +" not found");
            throw new UsernameNotFoundException(username +" not found");
        }
    }
}
